/*
 * @Author: youngqj youngqj@126.com
 * @Date: 2024-11-02 02:23:14
 * @LastEditors: youngqj youngqj@126.com
 * @LastEditTime: 2024-12-04 19:01:20
 * @FilePath: /mallSystem/core/utils/encryption.go
 * @Description:
 *
 * Copyright © Zhejiang Xiaoqu Information Technology Co., Ltd, All Rights Reserved.
 */
package utils

import (
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"errors"
)

var aesKey = []byte("7B5D837449686C6355079B2175F2CD35") // 32 字节的密钥

// Encrypt 加密函数
func Encrypt(text string) (string, error) {
	//fmt.Println("======>" + text)
	block, err := aes.NewCipher(aesKey)
	if err != nil {
		return "", err
	}

	plaintext := []byte(text)
	ciphertext := make([]byte, aes.BlockSize+len(plaintext))
	iv := ciphertext[:aes.BlockSize]
	stream := cipher.NewCFBEncrypter(block, iv)
	stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)

	return base64.URLEncoding.EncodeToString(ciphertext), nil
}

// Decrypt 解密函数
func Decrypt(cryptoText string) (string, error) {
	ciphertext, _ := base64.URLEncoding.DecodeString(cryptoText)
	//fmt.Println(ciphertext)
	block, err := aes.NewCipher(aesKey)
	if err != nil {
		return "", err
	}

	if len(ciphertext) < aes.BlockSize {
		return "", errors.New("ciphertext too short")
	}
	iv := ciphertext[:aes.BlockSize]
	ciphertext = ciphertext[aes.BlockSize:]

	stream := cipher.NewCFBDecrypter(block, iv)
	stream.XORKeyStream(ciphertext, ciphertext)
	//fmt.Println(string(ciphertext))

	return string(ciphertext), nil
}
